package com.kugou.miniapp.service;

import com.kugou.miniapp.dao.UserMapper;
import com.kugou.miniapp.domain.Friend;
import com.kugou.miniapp.domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class UserService {
    @Autowired(required = false)
    UserMapper userMapper;

    public List<Users> getFriend(String user_id){
        List<Friend> friends = userMapper.getFriendByUserId(user_id);
        List<Users> users = new LinkedList<>();
        for (Friend f: friends) {
//            String real_user_id = null;
//            if (!f.getUser_id_1().equals(user_id)){//和本身不相等，即是好友
//                real_user_id = f.getUser_id_1();
//            }else {//user_id_1和自身相等， 所以user_id_2才是好友
//                real_user_id = f.getUser_id_2();
//            }
            //好友用户基本信息
            Users u = userMapper.getUserByUserId(f.getUser_id_2());
            users.add(u);
        }
        return users;
    }

    //随机从数据库中获取一个用户
    public Users getOutLineUserInfo(String user_id) throws Exception {
        int count = userMapper.getUsersCount();
        int index = (int)(Math.random()*count);
        if (count <= 1){
            throw new Exception("目前系统不存在其他用户");
        }
        Users u = userMapper.getRandomOneUser(index);
        while (u.getUser_id().equals(user_id)){
            index = (int)(Math.random()*count);
            u = userMapper.getRandomOneUser(index);
        }
        return u;
    }

    //添加好友
    @Transactional
    public int beFriend(String user_id_1,String user_id_2){
        int i = userMapper.insertFriend(user_id_1, user_id_2);
        int j = userMapper.insertFriend(user_id_2, user_id_1);
        return i+j;
    }

    //添加用户到数据库
    public int addUser(Users user){
        return userMapper.insertUser(user);
    }

    public int updateUser(Users user){
        return userMapper.updateUser(user);
    }


    public Users getUserByUserId(String user_id){
        return userMapper.getUserByUserId(user_id);
    }

    public int delFriend(String my_user_id, String his_user_id) {
        Map<String, Object> con = new HashMap<>();
        con.put("my_user_id", my_user_id);
        con.put("his_user_id", his_user_id);
        return userMapper.delFriend(con);
    }
}
